import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '../config/config.service';
import { BinanceService } from '../binance/binance.service';
import { DeepSeekService } from '../deepseek/deepseek.service';
import { RiskManagementService } from './risk-management.service';
import {
  TradingSignal,
  TradingState,
  ExecutionResult,
  PerformanceMetrics,
} from './interfaces/trading.interface';
import { ConsensusDecision } from '../deepseek/interfaces/deepseek.interface';

@Injectable()
export class TradingService {
  private readonly logger = new Logger(TradingService.name);
  private tradingState: TradingState = {
    isActive: false,
    currentSymbol: this.configService.tradingSymbol,
    totalTrades: 0,
    successfulTrades: 0,
    failedTrades: 0,
    currentBalance: 0,
  };
  private tradeHistory: ExecutionResult[] = [];

  constructor(
    private configService: ConfigService,
    private binanceService: BinanceService,
    private deepSeekService: DeepSeekService,
    private riskManagementService: RiskManagementService,
  ) {
    this.initializeTradingState();
  }

  private initializeTradingState() {
    this.tradingState = {
      isActive: false,
      currentSymbol: this.configService.tradingSymbol,
      totalTrades: 0,
      successfulTrades: 0,
      failedTrades: 0,
      currentBalance: 0,
    };
  }

  // 启动自动交易
  async startTrading(): Promise<void> {
    try {
      this.logger.log('🚀 启动自动交易系统...');
      
      // 检查API连接
      await this.validateConnections();
      
      this.tradingState.isActive = true;
      this.logger.log('✅ 自动交易系统已启动');
      
      // 开始交易循环
      this.startTradingLoop();
    } catch (error) {
      this.logger.error('启动交易系统失败:', error);
      throw error;
    }
  }

  // 停止自动交易
  async stopTrading(): Promise<void> {
    this.logger.log('🛑 停止自动交易系统...');
    this.tradingState.isActive = false;
    this.logger.log('✅ 自动交易系统已停止');
  }

  // 验证API连接
  private async validateConnections(): Promise<void> {
    try {
      // 测试币安连接
      await this.binanceService.getCurrentPrice(this.tradingState.currentSymbol);
      this.logger.log('✅ 币安API连接正常');

      // 测试账户信息
      await this.binanceService.getAccountInfo();
      this.logger.log('✅ 账户信息获取正常');

      // 确保对冲模式已启用
      const hedgeModeEnabled = await this.binanceService.ensureHedgeMode();
      if (!hedgeModeEnabled) {
        throw new Error('无法启用对冲模式，请检查账户设置');
      }

      this.logger.log('✅ 所有API连接验证通过');
    } catch (error) {
      this.logger.error('API连接验证失败:', error);
      throw error;
    }
  }

  // 主交易循环
  private async startTradingLoop(): Promise<void> {
    while (this.tradingState.isActive) {
      try {
        // 应急止损检查
        const emergencyCheck = await this.riskManagementService.emergencyStopCheck();
        if (emergencyCheck.shouldStop) {
          this.logger.error(`🚨 应急停止: ${emergencyCheck.reason}`);
          await this.stopTrading();
          break;
        }

        // 执行交易分析和决策
        await this.executeTradingCycle();

        // 等待下一个分析周期
        const intervalMs = this.configService.analysisInterval;
        this.logger.log(`⏰ 等待下一个分析周期: ${intervalMs}ms (${intervalMs/1000/60}分钟)`);
        await this.sleep(intervalMs);
      } catch (error) {
        this.logger.error('交易循环出错:', error);
        await this.sleep(30000); // 出错后等待30秒再继续
      }
    }
  }

  // 执行一个完整的交易周期
  private async executeTradingCycle(): Promise<void> {
    try {
      this.logger.log('📊 开始新的交易分析周期...');

      // 1. 获取市场数据
      const marketData = await this.gatherMarketData();
      
      // 2. 获取账户信息
      const accountInfo = await this.binanceService.getAccountInfo();
      const allPositions = await this.binanceService.getPositions();
      const positions = allPositions.filter(pos => pos.symbol === this.tradingState.currentSymbol);

      // 3. 多角色AI分析
      this.logger.log('🤖 开始多角色AI分析...');
      const analyses = await this.deepSeekService.multiRoleAnalysis(
        marketData,
        accountInfo,
        positions,
        marketData.klineData,
      );

      // 4. 生成最终决策
      const decision = await this.deepSeekService.generateConsensusDecision(
        analyses,
        marketData,
        accountInfo,
      );

      // 5. 显示分析结果
      this.displayAnalysisResults(analyses, decision);

      // 6. 执行交易决策
      if (decision.finalAction !== 'HOLD') {
        await this.executeDecision(decision);
      }

      // 记录分析时间
      this.logger.log('完成一轮交易分析');
      this.logger.log('✅ 交易周期完成\n');
    } catch (error) {
      this.logger.error('交易周期执行失败:', error);
    }
  }

  // 收集市场数据
  private async gatherMarketData(): Promise<any> {
    const symbol = this.tradingState.currentSymbol;
    
    const [currentPrice, stats24hr, klineData] = await Promise.all([
      this.binanceService.getCurrentPrice(symbol),
      this.binanceService.get24hrStats(symbol),
      this.binanceService.getKlineData(symbol, this.configService.tradingInterval, 100),
    ]);

    return {
      currentPrice,
      stats24hr,
      klineData,
      timestamp: Date.now(),
    };
  }

  // 显示分析结果
  private displayAnalysisResults(analyses: any[], decision: ConsensusDecision): void {
    console.log('\n' + '='.repeat(80));
    console.log('📈 AI交易分析报告');
    console.log('='.repeat(80));
    
    // 显示各角色分析
    analyses.forEach(analysis => {
      console.log(`\n🎭 ${this.getRoleDisplayName(analysis.role)}:`);
      console.log(`   建议: ${analysis.recommendation.action}`);
      console.log(`   置信度: ${analysis.confidence}%`);
      console.log(`   紧急程度: ${analysis.recommendation.urgency}`);
      console.log(`   理由: ${analysis.reasoning.substring(0, 100)}...`);
    });

    // 显示最终决策
    console.log('\n' + '-'.repeat(50));
    console.log('🎯 最终交易决策:');
    console.log(`   动作: ${decision.finalAction}`);
    console.log(`   数量: ${decision.quantity}`);
    console.log(`   价格: ${decision.price || '市价'}`);
    console.log(`   止损: ${decision.stopLoss || 'N/A'}`);
    console.log(`   止盈: ${decision.takeProfit || 'N/A'}`);
    console.log(`   杠杆: ${decision.leverage || 'N/A'}x`);
    console.log(`   置信度: ${decision.confidence}%`);
    console.log(`   决策理由: ${decision.reasoning.substring(0, 150)}...`);
    console.log('='.repeat(80));
  }

  // 获取角色显示名称
  private getRoleDisplayName(role: string): string {
    const roleNames = {
      'technical_analyst': '技术分析师',
      'fundamental_analyst': '基本面分析师',
      'risk_manager': '风险管理师',
      'news_analyst': '消息面分析师',
      'execution_officer': '交易执行官',
    };
    return roleNames[role] || role;
  }

  // 执行交易决策
  private async executeDecision(decision: ConsensusDecision): Promise<void> {
    try {
      // 转换为交易信号
      const signal: TradingSignal = {
        symbol: this.tradingState.currentSymbol,
        action: decision.finalAction,
        quantity: decision.quantity,
        price: decision.price,
        stopLoss: decision.stopLoss,
        takeProfit: decision.takeProfit,
        leverageRecommendation: decision.leverage,
        confidence: decision.confidence,
        reasoning: decision.reasoning,
        timestamp: decision.timestamp,
        urgency: 'MEDIUM',
      };

      // 风险检查
      const riskCheck = await this.riskManagementService.canExecuteTrade(signal);
      if (!riskCheck.canTrade) {
        this.logger.warn(`❌ 交易被风险管理拒绝: ${riskCheck.reason}`);
        return;
      }

      // 获取风险评估
      const accountInfo = await this.binanceService.getAccountInfo();
      const positions = await this.binanceService.getPositions();
      const riskAssessment = await this.riskManagementService.assessRisk(
        accountInfo,
        positions,
        signal,
      );

      // 调整交易参数
      signal.quantity = riskAssessment.positionSizeRecommendation;
      signal.stopLoss = riskAssessment.stopLossRecommendation;
      signal.takeProfit = riskAssessment.takeProfitRecommendation;
      signal.leverageRecommendation = riskAssessment.leverageRecommendation;

      this.logger.log(`💼 执行交易: ${signal.action} ${signal.quantity} ${signal.symbol}`);

      // 执行交易
      const result = await this.executeTrade(signal);
      
      if (result.success) {
        this.logger.log(`✅ 交易执行成功: 订单ID ${result.orderId}`);
        this.tradingState.totalTrades++;
        this.tradingState.successfulTrades++;
      } else {
        this.logger.error(`❌ 交易执行失败: ${result.error}`);
        this.tradingState.totalTrades++;
      }

      this.tradeHistory.push(result);
    } catch (error) {
      this.logger.error('执行交易决策失败:', error);
    }
  }

  // 执行具体交易
  private async executeTrade(signal: TradingSignal): Promise<ExecutionResult> {
    try {
      // 设置杠杆（如果提供了杠杆推荐值）
      if (signal.leverageRecommendation && signal.leverageRecommendation > 0) {
        try {
          await this.setLeverage(signal.symbol, signal.leverageRecommendation);
        } catch (leverageError) {
          this.logger.warn(`杠杆设置失败，继续执行交易: ${leverageError.message}`);
        }
      }

      let orderResult;

      switch (signal.action) {
        case 'BUY':
          if (signal.price) {
            orderResult = await this.binanceService.limitBuy(
              signal.symbol,
              signal.quantity,
              signal.price,
              'LONG', // 买入开多仓
            );
          } else {
            orderResult = await this.binanceService.marketBuy(
              signal.symbol,
              signal.quantity,
              'LONG', // 买入开多仓
            );
          }
          break;

        case 'SELL':
          if (signal.price) {
            orderResult = await this.binanceService.limitSell(
              signal.symbol,
              signal.quantity,
              signal.price,
              'SHORT', // 卖出开空仓
            );
          } else {
            orderResult = await this.binanceService.marketSell(
              signal.symbol,
              signal.quantity,
              'SHORT', // 卖出开空仓
            );
          }
          break;

        case 'CLOSE':
          // 平仓逻辑 - 对冲模式下需要分别处理多空仓位
          const allPositions = await this.binanceService.getPositions();
          const positions = allPositions.filter(pos => pos.symbol === signal.symbol && Math.abs(pos.positionAmt) > 0);
          
          for (const position of positions) {
            if (Math.abs(position.positionAmt) > 0) {
              const quantity = Math.abs(position.positionAmt);
              const positionSide = position.positionSide;
              
              if (positionSide === 'LONG') {
                // 平多仓：卖出
                orderResult = await this.binanceService.marketSell(
                  signal.symbol,
                  quantity,
                  'LONG'
                );
              } else if (positionSide === 'SHORT') {
                // 平空仓：买入
                orderResult = await this.binanceService.marketBuy(
                  signal.symbol,
                  quantity,
                  'SHORT'
                );
              }
              this.logger.log(`✅ 平仓成功: ${positionSide} ${quantity} ${signal.symbol}`);
            }
          }
          break;

        default:
          throw new Error(`不支持的交易动作: ${signal.action}`);
      }

      // 设置止损止盈
      if (orderResult && signal.stopLoss) {
        await this.setStopLoss(signal);
      }
      if (orderResult && signal.takeProfit) {
        await this.setTakeProfit(signal);
      }

      return {
        success: true,
        orderId: orderResult?.orderId,
        executedQuantity: parseFloat(orderResult?.executedQty || '0'),
        executedPrice: parseFloat(orderResult?.avgPrice || '0'),
        timestamp: new Date(),
      };
    } catch (error) {
      return {
        success: false,
        error: error.message,
        timestamp: new Date(),
      };
    }
  }

  // 设置止损
  private async setStopLoss(signal: TradingSignal): Promise<void> {
    try {
      // 对冲模式下的止损逻辑
      let side: 'BUY' | 'SELL';
      let positionSide: 'LONG' | 'SHORT';
      
      if (signal.action === 'BUY') {
        // 买入开多仓，止损用卖出平多仓
        side = 'SELL';
        positionSide = 'LONG';
      } else {
        // 卖出开空仓，止损用买入平空仓
        side = 'BUY';
        positionSide = 'SHORT';
      }
      
      await this.binanceService.setStopLoss(
        signal.symbol,
        signal.quantity,
        signal.stopLoss,
        side,
        positionSide,
      );
      this.logger.log(`✅ 止损单设置成功: ${signal.stopLoss}`);
    } catch (error) {
      this.logger.error('设置止损失败:', error);
    }
  }

  // 设置止盈
  private async setTakeProfit(signal: TradingSignal): Promise<void> {
    try {
      // 对冲模式下的止盈逻辑
      let side: 'BUY' | 'SELL';
      let positionSide: 'LONG' | 'SHORT';
      
      if (signal.action === 'BUY') {
        // 买入开多仓，止盈用卖出平多仓
        side = 'SELL';
        positionSide = 'LONG';
      } else {
        // 卖出开空仓，止盈用买入平空仓
        side = 'BUY';
        positionSide = 'SHORT';
      }
      
      await this.binanceService.setTakeProfit(
        signal.symbol,
        signal.quantity,
        signal.takeProfit,
        side,
        positionSide,
      );
      this.logger.log(`✅ 止盈单设置成功: ${signal.takeProfit}`);
    } catch (error) {
      this.logger.error('设置止盈失败:', error);
    }
  }

  // 设置杠杆
  private async setLeverage(symbol: string, leverage: number): Promise<void> {
    try {
      await this.binanceService.setLeverage(symbol, leverage);
      this.logger.log(`✅ 杠杆设置成功: ${symbol} - ${leverage}x`);
    } catch (error) {
      this.logger.error(`设置杠杆失败 ${symbol} ${leverage}x:`, error);
      throw error;
    }
  }

  // 获取交易状态
  getTradingState(): TradingState {
    return { ...this.tradingState };
  }

  // 获取性能指标
  getPerformanceMetrics(): PerformanceMetrics {
    const totalTrades = this.tradeHistory.length;
    const profitableTrades = this.tradeHistory.filter(trade => trade.success && trade.pnl > 0).length;
    const winRate = totalTrades > 0 ? (profitableTrades / totalTrades) * 100 : 0;
    
    const pnlValues = this.tradeHistory.map(trade => trade.pnl || 0);
    const totalReturn = pnlValues.reduce((sum, pnl) => sum + pnl, 0);
    const averageReturn = totalTrades > 0 ? totalReturn / totalTrades : 0;
    const maxDrawdown = this.calculateMaxDrawdown(pnlValues);
    const sharpeRatio = this.calculateSharpeRatio(pnlValues);

    return {
      totalReturn,
      winRate,
      maxDrawdown,
      sharpeRatio,
      averageReturn,
      totalTrades,
      profitableTrades,
    };
  }

  // 计算最大回撤
  private calculateMaxDrawdown(pnlValues: number[]): number {
    if (pnlValues.length === 0) return 0;
    
    let maxDrawdown = 0;
    let peak = 0;
    let cumulative = 0;
    
    for (const pnl of pnlValues) {
      cumulative += pnl;
      if (cumulative > peak) {
        peak = cumulative;
      }
      const drawdown = (peak - cumulative) / Math.max(peak, 1) * 100;
      if (drawdown > maxDrawdown) {
        maxDrawdown = drawdown;
      }
    }
    
    return maxDrawdown;
  }

  // 计算夏普比率
  private calculateSharpeRatio(pnlValues: number[]): number {
    if (pnlValues.length < 2) return 0;
    
    const mean = pnlValues.reduce((sum, val) => sum + val, 0) / pnlValues.length;
    const variance = pnlValues.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / pnlValues.length;
    const stdDev = Math.sqrt(variance);
    
    return stdDev > 0 ? mean / stdDev : 0;
  }

  // 私有辅助方法
  private async sleep(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
  }
}